import {login, logout} from "@/api/login";
import {LoginForm} from "@/api/login/types";
import {getUserInfo} from "@/api/user";
import {getToken, removeToken, setToken} from "@/utils/token";
import {defineStore} from "pinia";
import {UserState} from "../interface";
import {CardForm} from "@/api/card/types";
import {getCardList} from "@/api/card";

const useUserStore = defineStore("useUserStore", {
    state: (): UserState => ({
        id: null,
        avatar: "",
        cardList: [] as CardForm[],
    }),
    actions: {
        LogIn(LoginForm: LoginForm) {
            return new Promise((resolve, reject) => {
                login(LoginForm)
                    .then(({data}) => {
                        // 请求成功时被调用
                        if (data.flag) {
                            setToken(data.data);
                            resolve(data);
                        } else {
                            reject(data.msg);
                        }
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        GetInfo() {
            return new Promise((resolve, reject) => {
                getUserInfo()
                    .then(({data}) => {
                        if (data.flag) {
                            this.id = data.data.id;
                            this.avatar = data.data.avatar;
                        }
                        resolve(data);
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        LogOut() {
            return new Promise((resolve, reject) => {
                logout()
                    .then(() => {
                        this.id = null;
                        this.avatar = "";
                        removeToken();
                        console.log(getToken())
                        resolve(null);
                        window.location.reload();
                    })
                    .catch((error) => {
                        reject(error);
                    });
            });
        },
        setCardList() {
            getCardList().then(({data}) => {
                if (data.flag){
                    this.cardList = data.data;
                }
            })
        },
    },
    getters: {},
});

export default useUserStore;
